<?php
/*
 * 用户中心
 */
namespace Mobile\Controller;
use Mobile\Model\gradeModel;

use Mobile\Model\memberModel;
use Mobile\Model\orderModel;
use Mobile\Model\tmpmsgModel;

class UserController extends BaseController {
    
    public $gradeModel;
    public $memberModel;
    public $orderModel;
    public $kinglist;
    
    public $grade_arr;
    public $smscodeModel;
    public function __construct() {
        parent::__construct();
        $this->gradeModel = new gradeModel();
        $this->memberModel = new memberModel();
        $this->orderModel = new orderModel();
        $this->grade_arr = $this->_get_gradename();
        $this->smscodeModel = new \Mobile\Model\smscodeModel();
        $BindController = new BindController();
        $BindController->autobind();
    }
    
    protected function _get_gradename(){
        $where = array();
        $grade_list = $this->gradeModel->getGradeList($where);
        
        $new_grade = array();
        foreach($grade_list as $k=>$v){
            $new_grade[$v['grade_id']] = $v['grade_name'];
        }
        return $new_grade;
    }
     /*
     * 获取一级下级
     */
    protected function _get_xiaji($uid){
    
        $page = get("p",1);
        //获取我的一级下级
        $where = array(
            "refer_uid" => $uid
        );
        $xiaji = $this->memberModel->where($where)->field("grade_id,nickname,realname,mobile,headimgurl,uid,refer_uid")->order("grade_id DESC,uid DESC")->page($page,15)->select();
    
        return $xiaji;
    }
    
    
    protected function _get_xiaji_count($uid){
    
        //获取我的一级下级
        $where = array(
            "refer_uid" => $uid
        );
        $xiaji = $this->memberModel->where($where)->count();
    
        return $xiaji ? $xiaji : 0;
    }
    
    
    /*
     * 获取2级下级
     */
    protected function _get_xiaji2($uid){
    
        $page = get("p",1);
        //获取我的一级下级
        $where = array(
            "refer_uid" => $uid
        );
        $a_xiaji = $this->memberModel->where($where)->field("uid")->select();
        if(empty($a_xiaji)){
            return false;
        }
    
        $uids = array();
        foreach($a_xiaji as $k=>$v){
            $uids[] = $v['uid'];
        }
    
        //获取我的2级下级
        $where = array(
            "refer_uid" => array("IN",$uids)
        );
        $xiaji = $this->memberModel->where($where)->field("grade_id,nickname,realname,mobile,headimgurl,uid")->order("grade_id DESC,uid DESC")->page($page,15)->select();
        return $xiaji;
    }
    
    protected function _get_xiaji_count2($uid){
    
        //获取我的一级下级
        $where = array(
            "refer_uid" => $uid
        );
        $a_xiaji = $this->memberModel->where($where)->field("uid")->select();
        if(empty($a_xiaji)){
            return 0;
        }
    
        $uids = array();
        foreach($a_xiaji as $k=>$v){
            $uids[] = $v['uid'];
        }
    
        //获取我的2级下级
        $where = array(
            "refer_uid" => array("IN",$uids)
        );
        $xiaji = $this->memberModel->where($where)->count();
        return $xiaji ? $xiaji : 0;
    }
    
    /*
     * 获取3级下级
     */
    protected function _get_xiaji3($uid){
    
        $page = get("p",1);
        //获取我的一级下级
        $where = array(
            "refer_uid" => $uid
        );
        $a_xiaji = $this->memberModel->where($where)->field("uid")->select();
        if(empty($a_xiaji)){
            return false;
        }
    
        $uids = array();
        foreach($a_xiaji as $k=>$v){
            $uids[] = $v['uid'];
        }
    
        //获取我的2级下级
        $where_b = array(
            "refer_uid" => array("IN",$uids)
        );
        $b_xiaji = $this->memberModel->where($where_b)->field("uid")->select();
        if(empty($b_xiaji)){
            return false;
        }
        $uids = array();
        foreach($b_xiaji as $k=>$v){
            $uids[] = $v['uid'];
        }
        $where_c = array(
            "refer_uid" => array("IN",$uids)
        );
    
        $xiaji = $this->memberModel->where($where_c)->field("grade_id,nickname,realname,mobile,headimgurl,uid")->order("grade_id DESC,uid DESC")->page($page,15)->select();
        return $xiaji;
    }
    
    protected function _get_xiaji_count3($uid){
    
        //获取我的一级下级
        $where = array(
            "refer_uid" => $uid
        );
        $a_xiaji = $this->memberModel->where($where)->field("uid")->select();
        if(empty($a_xiaji)){
            return false;
        }
    
        $uids = array();
        foreach($a_xiaji as $k=>$v){
            $uids[] = $v['uid'];
        }
    
        //获取我的2级下级
        $where_b = array(
            "refer_uid" => array("IN",$uids)
        );
        $b_xiaji = $this->memberModel->where($where_b)->field("uid")->select();
        if(empty($b_xiaji)){
            return 0;
        }
        $uids = array();
        foreach($b_xiaji as $k=>$v){
            $uids[] = $v['uid'];
        }
        $where_c = array(
            "refer_uid" => array("IN",$uids)
        );
    
        $xiaji = $this->memberModel->where($where_c)->count();
        return $xiaji ? $xiaji : 0;
    }
    /*
     * 我的代理
     */
    public function daili(){
        
//        layout("Mui/layout");
        $page = get('p',1);//页面
        $page_size = 10;
//        $where = array(
//            "refer_uid" => $this->uid,
//            'grade_id' => array('egt',2)
//        );
        $uid = $this->uid;
        if($_GET['uid']){
            $uid = $_GET['uid'];
        }
        
        //等级
        $gradelist = $this->gradeModel->select();
        unset($gradelist[4]);
        unset($gradelist[5]);
        $this->assign('gradelist',$gradelist);
        
        $user = $this->memberModel->where(array('uid'=>$uid))->find();
        
        $this->assign('user',$user);
        $a_daili = $this->_get_xiaji($uid);
        $a_count = $this->_get_xiaji_count($uid);
        foreach ($a_daili as $k=>$v){
            $daili[$k] = $v;
            $daili[$k]['grade_name'] = $this->_mygrade($v);//获取用户等级
            $daili[$k]['floor'] = $this->_getDailiFloor($v);
            
//            $daili[$k]['grade3_uid'] = $this->_getDailiRefer($v);
//            if($daili[$k]['grade3_uid']!=$this->uid && $v['grade_id']<4) {
//                unset($daili[$k]);
//            }
            
//            if($v['grade_id']<4 && $v['refer_uid']!=$this->memberinfo['uid']) {
//                unset($daili[$k]);
//            }
            
        }
        //$count = $this->memberModel->where($where)->count();
        $this->assign("dailinums",$a_count);
        $totalpage = ceil($a_count/10);//向上取整,总的页码数
        $this->assign('totalpage',$totalpage);
        if(IS_AJAX){
            exit_json($daili);
        }
        $seo_data = array(
            "title" => "我的".C('XIAJI_NAME'),
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
        $share_data = array(
            "title" => "我的".C('XIAJI_NAME'),
        );
        $this->setShare($share_data);
        
        //计算团队总销量
        $jinhuo_nums = $this->memberinfo['jinhuo_nums'];
        $xiajilist = $this->memberModel->where(array('refer_uid'=>$this->uid))->select();
        foreach ($xiajilist as $xiaji) {
            $jinhuo_nums += $xiaji['jinhuo_nums'];
        }
		
		
		
        $this->assign('jinhuo_nums',$jinhuo_nums);
        
        $this->display('daili2');
    }
    
    protected function _getDailiFloor ($user) {
        $refer = $user;
        $floor = 1;
        while ($refer) {
            $refer = $this->memberModel->where(array('uid'=>$refer['refer_uid']))->find();
            if($refer['uid']==$this->uid) {
                break;
            }
            if(!$refer) {
                $floor = 0;
                break;
            }else{
                $floor++;
            }
        }
        return $floor;
    }
    
    protected function _getDailiRefer ($user) {
        $refer = $user;
        while ($refer) {
            if($refer['grade_id']>=4) {
                return $refer['uid'];
            }
            $refer = $this->memberModel->where(array('uid'=>$refer['refer_uid']))->find();
        }
        return false;
    }

    protected function _mygrade($userinfo=array()){
        
        if(!$userinfo){
            $userinfo = $this->memberinfo;
        }

        $user_grade = $this->grade_arr[$userinfo['grade_id']];
        return $user_grade;
    }
    
    
    public function index(){
        //parent::wxLogin();
        $seo_data = array(
            "title" => $this->lang['user_index'],
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
		
        if($this->memberinfo['refer_uid']){
            $referinfo = $this->memberModel->where(array('uid'=>$this->memberinfo['refer_uid']))->find();
            $this->assign("refer",$referinfo);
        }
        
        $user_grade = $this->_mygrade();//我的等级
        $this->assign('user_grade',$user_grade);//用户等级
        
        $order_count = A("Orderlists")->countOrder($this->uid);
        $this->assign("order_count",$order_count);

        $share_data = array(
            "title" => $this->lang['user_index'],
        );
        
        $time = strtotime(date('Y-m-01'));
        $start = date('Y-m-d 00:00:00', strtotime('+0 month',$time));
        $end = date('Y-m-d 00:00:00', strtotime('+1 month',$time));
        
        $uid = $this->uid;
        $mydata = array(
            'mymoney' => _getMyMoney($uid),
            'teammoney' => _getTeamMoney($uid),
            'month_mymoney' => _getMyMoney($uid, $start, $end),
            'month_teammoney' => _getTeamMoney($uid, $start, $end),
            'refer_money' => getReferMoney($uid)
        );
        
        
        //月度返利
        $mmoney = monthYeji($uid, $start, $end);
        //年度返利
        if($mydata['mymoney']>=200000) {
            $ymoney = $mydata['mymoney']*0.011;
        }
        if($mydata['mymoney']>=300000){
            $ymoney = $mydata['mymoney']*0.012;
        }
        if($mydata['mymoney']>=500000){
            $ymoney = $mydata['mymoney']*0.013;
        }if($mydata['mymoney']>=1000000){
            $ymoney = $mydata['mymoney']*0.014;
        }
        if($mydata['mymoney']>=2000000){
            $ymoney = $mydata['mymoney']*0.015;
        }
        if($mydata['mymoney']>=5000000){
            $ymoney = $mydata['mymoney']*0.016;
        }
        if($mydata['mymoney']>=8000000){
            $ymoney = $mydata['mymoney']*0.017;
        }
        if($mydata['mymoney']>=13000000){
            $ymoney = $mydata['mymoney']*0.018;
        }
        if($mydata['mymoney']>=20000000){
            $ymoney = $mydata['mymoney']*0.019;
        }
        if($mydata['mymoney']>=30000000){
            $ymoney = $mydata['mymoney']*0.02;
        }
        
        $mydata['month_fanli'] = $mmoney>0?$mmoney:0;
        $mydata['year_fanli'] = $ymoney>0?$ymoney:0;
        
        
        $this->assign('mydata',$mydata);
        
        
        $this->setShare($share_data);
        
        $this->display();
    }
    
    /*
     * 等级特权
     */
    public function grade(){
        $seo_data = array(
            "title" => $this->lang['user_grade'],
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
        
        $user_grade = $this->_mygrade();//我的等级
        $this->assign('user_grade',$user_grade);//用户等级
        
        $where = array();
        $grade_list = $this->gradeModel->getGradeList($where);
        $this->assign('datalist',$grade_list);

        $share_data = array(
            "title" => $this->lang['user_grade'],
        );
        $this->setShare($share_data);
        
        $this->display();
    }
    
    
    /*
     * 定时升级等级
     */
    public function cronupgrade(){
    
        $res1 = $this->_ceo2king();
        $res2 = $this->_king2big();
    
        return_json(0,"SUCCESS",$res1+$res2);
    
    }
    
    //CEO升级为皇冠
    protected function _ceo2king(){
        
        $i = 0;
        //查找出所有的CEO
        $where = array(
            "grade_id" => 2
        );
        $memberlist = $this->memberModel->where($where)->field("uid,refer_uid,grade_id,realname,openid")->select();
        foreach($memberlist as $k=>$v){
    
            //查找该ceo直属下级CEO数量
            $count = 0;
            $where_ceo = array(
                "grade_id" => array(
                    "egt",2
                ),
                "refer_uid" => $v['uid']
            );
            $count = $this->memberModel->where($where_ceo)->count();
            if($count>=6){
                //该ceo升级为皇冠等级
                $where_me = array(
                    "uid" => $v['uid']
                );
                $this->memberModel->where($where_me)->setField("grade_id",3);
                //升级为ceo
                
                $this->_shengjiMsg($v,2,3);
                
                $content = "(系统操作)".$this->grade_arr[2]."->".$this->grade_arr[3];
                $this->_upgradelog($v, $content);//升级日志
                $i++;
                
            }
        }
    
        return $i;
    
    }
    
    
    /*
     * 皇冠升级为大皇冠
     */
    protected function _king2big(){
    
        $i = 0;
        //查找出所有的皇冠
        $where = array(
            "grade_id" => 3
        );
        $memberlist = $this->memberModel->where($where)->field("uid,refer_uid,grade_id,realname,openid")->select();
        foreach($memberlist as $k=>$v){
    
            $where_me = array(
                "uid" => $v['uid']
            );
    
            //查找该皇冠直属下级皇冠数量
            $count = 0;
            $where_king = array(
                "grade_id" => array(
                    "egt",3
                ),
                "refer_uid" => $v['uid']
            );
            $count = $this->memberModel->where($where_king)->count();
            if($count == 0){
                continue;//中断
            }
    
    
            if($count>=6){
                //该皇冠升级为大皇冠等级
                $this->memberModel->where($where_me)->setField("grade_id",4);
                
                $this->_shengjiMsg($v,3,4);
                
                $content = "(系统操作)".$this->grade_arr[3]."->".$this->grade_arr[4];
                $this->_upgradelog($v, $content);//升级日志
                $i++;
                continue;//中断
            }
    
    
    
            //一级不足六人,查找二级
            $uid_arr = array();//清空数组
            $first_king = $this->memberModel->where($where_king)->field("uid,refer_uid,grade_id,realname,openid")->select();
            foreach($first_king as $kk=>$vv){
                $uid_arr[] = $vv['uid'];
            }
    
            $count2 = 0;
            $where_king2 = array(
                "grade_id" => array(
                    "egt",3
                ),
                "refer_uid" => array(
                    "IN",$uid_arr
                )
            );
            $count2 = $this->memberModel->where($where_king2)->count();
            if($count2+$count >=6 ){
                //该皇冠升级为大皇冠等级
                $this->memberModel->where($where_me)->setField("grade_id",4);
                $this->_shengjiMsg($v,3,4);
                
                $content = "(系统操作)".$this->grade_arr[3]."->".$this->grade_arr[4];
                $this->_upgradelog($v, $content);//升级日志
                $i++;
            }
        }
        
        return $i;
        
    }
   
    
    /*
     * actionlog   1等级变更   3手机号码变更 日志
     */
    protected function _upgradelog($userinfo,$content){
    
        $change = array(
            "log_type" => 1,
            "action_username" => "system_cron",
            "target_uid" => $userinfo["uid"],
            "target_username" => $userinfo["realname"],
            "create_time" => date('Y-m-d H:i:s'),
            "content" => $content
        );
        $m = M("actionlog");
        $m->add($change);
    
    }
    

    /*
     * 升级通知,模板消息
     *
     */
    protected function _shengjiMsg($userinfo,$old,$new){
    
        //发送升级模板消息
    
        //发送模板消息
        $msg = $this->_sendsjmsgtmp($userinfo,$old,$new);//拼接模板消息
    
        $msgttt = array(
            "uid" => $userinfo['uid'],
            "openid" => $userinfo['openid'],
            "nickname" => $userinfo['realname'],
            "groupid" => -1,
            "content" => $msg,
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        $tmpmsgModel = new tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
    
        return true;
    }
    
    
    /*
     * 升级消息
     *
     */
    protected function _sendsjmsgtmp($userinfo,$old,$new){
    
        $grade_arr = $this->grade_arr;
    
        $tmp_id = $this->tmpl['DENG_JI']['tmp_id'];
        $color = $this->tmpl['DENG_JI']['color'];
    
        $url = get_domain()."/mobile/user/grade/";
        $footer ='\\n'."点击查看详情...";
        $msg = array(
            "touser" => $userinfo['openid'],
            "template_id" => $tmp_id,//
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode("恭喜,你的等级已提升~".'\\n'),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode($grade_arr[$old]),//原先等级
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode($grade_arr[$new]),//new等级
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
    
        return $msg = urldecode(json_encode($msg));
    }
    
    
     /*
        * 下载图片
    */
    public function downloadpic(){

        $dtype = get('dtype');
        //下载图片并上传到云服务器
        $upload = new \Think\Upload();
        $upload->rootPath  =  "/";
        $upload->savePath  = "/upload/".$dtype."/";
        $filrInfo   =   $upload->upload();

        if($filrInfo){
            $thumb_url = $filrInfo['file']['savepath'].$filrInfo['file']['savename'];//拼接图片网址

             //为用户存储头像
            $this->memberModel->where(array('uid'=>$this->uid))->setField('headimgurl',C('UPYUN_DOMAIN').$thumb_url);

            return_json(0,"",$thumb_url);
        }
        return_json(1,"网络不给力,请重新上传~"); 
    }
    
    public function dailiorder () {
        if(IS_AJAX) {
            $uid = get('uid');
            $member = $this->memberModel->where(array('uid'=>$uid))->find();
            if($member['refer_uid']!=$this->uid){
                return false;
            }
            $where = array(
                'uid' => $uid,
                'checked' => array('in',array('1,2,5')),
            );
            $page = get('p',1);
            $size = 5;
            $list = $this->orderModel->where($where)->order('order_id DESC')->page($page,$size)->select();
            foreach ($list as $k=>$v) {
                $list[$k]['goods'] = unserialize($v['goods']);
                $list[$k]['delivery'] = unserialize($v['delivery']);
            }
            return_json(0,'success',$list);
        }
        $seo_data = array(
            "title" => '下级订单',
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
        $this->display();
    }
    
    public function myinfo () {
        $seo_data = array(
            "title" => '我的信息',
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
        $this->display();
    }
    
    
    public function tongji () {
        $seo_data = array(
            "title" => '销售额统计',
            "description" => "",
            "keywords" => "",
        );
        $start = date('Y-m-01 00:00:00');
        $end = date('Y-m-01 00:00:00', strtotime('+1 month'));
        $list = array();
        for($i=1;$i<5;$i++) {
            if($start<'2017-08-01 00:00:00'){
                break;
            }
            $list[$i]['time'] = date('Y-m', strtotime($start));
            $list[$i]['money'] = $this->_getXiaoshou($start, $end);
            $start = date('Y-m-01 00:00:00', strtotime("-{$i} month"));
            $x = $i-1;
            $end = date('Y-m-01 00:00:00', strtotime("-{$x} month"));
            
        }
        $this->assign('datalist',$list);
        $this->setSeo($seo_data);
        $this->display();
    }
    
    protected function _getXiaoshou ($start,$end) {
        $uids = $this->memberModel->where(array('refer_uid'=>$this->uid))->getField('uid',true);
        if(empty($uids)) {
            $uids = array(0);
        }
        $where = array(
            'pay_time' => array('between',array($start,$end)),
            'uid' => array('in',$uids),
            'checked' => array('in',array(1,2,5))
        );
        $money = $this->orderModel->where($where)->sum('order_cashmoney');
        return $money ? $money : 0;
    }
    
    public function changepaypw () {
        layout('Mui/layout');
        $seo = array(
            'title' => '修改支付密码',
        );
        if(IS_AJAX) {
            $allow = array(
                'password_old','password_new1','password_new2'
            );
            $data = param_filter($_POST, $allow,$allow,false,true);
            if(empty($data)) {
                return_json(1,'请填写完整');
            }
            $member = $this->memberModel->where(array('uid'=> $this->uid))->find();
            if(md5($data['password_old'])!=$member['pay_password']) {
                return_json(1,'旧密码输入错误');
            }
            if($data['password_new1']!=$data['password_new2']) {
                return_json(1,'两次密码输入不一致');
            }
            if(strlen($data['password_new1'])<6) {
                return_json(1,'支付密码至少6位');
            }
            $saveData = array(
                'pay_password' => md5($data['password_new1'])
            );
            $res = $this->memberModel->where(array('uid'=>$this->uid))->save($saveData);
            if($res) {
                return_json(0,'修改成功');
            }
            return_json(1,'新密码与旧密码一致');
        }
        $this->setSeo($seo);
        $this->display();
    }
    
    public function getsmscode () {
        if(!$this->memberinfo['mobile']) {
            return_json(1,'清联系客服完善手机号码');
        }
        $code = $this->sendsms();
//        $code = '1234';
        session('SMSCODE',$code);
        return_json(0,'发送成功');
    }
    
    public function kefu () {
        $refer = $this->memberinfo;
        while (!empty($refer)) {
            if($refer['refer_uid']==6600) {
                break;
            }
            $refer = $this->memberModel->where(array('uid'=>$refer['refer_uid']))->find();
        }
        if($refer && $refer['uid']!=$this->memberinfo['uid']) {
            $this->assign('kefu',$refer);
            $this->display();exit;
        }
        $this->error2('暂无专属客服');
    }
    protected function sendsms(){
       
        $mobile = $this->memberinfo['mobile'];
        if(!check_mobile($mobile)){
            return_json(1,"请检查手机号是否正确");
        }
        if(!IS_AJAX){
            return_json(1,"提交方式有误");
        }

        //发送短信
        $code = rand(1000,9999);
        $data = array(
            "code" => "$code",
            "product" => "善婷生物"
        );
        //将信息存储到数据库
        $save_data = array(
            "uid" => $this->uid,
            "smssign" => C('ALIDAYU_SIGN'),
            "mobile" => $mobile,
            "tmpid" => C('ALIDAYU_SHENFEN_TMP'),
            "content" => json_encode($data),
            "code" => $code,
            "create_time" => date("Y-m-d H:i:s"),
            "expired_time" => date("Y-m-d H:i:s",time()+5*60),
            "ip" => get_client_ip(),
            "try_time" => 0,
            "status" => 1,
        );
        
        $res = alisms(C('ALIDAYU_SIGN'),$mobile,C('ALIDAYU_SHENFEN_TMP'),$data);
        if($res['result']['success']){
            $save_data['send_status'] = 1;
            $code_id = $this->smscodeModel->addSmscode($save_data);
            return $code;
        }else{
            $msg = "发送失败,请稍后重试。错误原因:".$res['sub_msg'];
            $save_data['send_status'] = 0;
            $this->smscodeModel->addSmscode($save_data);
            return_json(1,$msg);
        }
        
    }
    
    public function changegrade() {
        $uid = $_POST['uid'];
        $grade_id = $_POST['grade_id'];
        $cuser = $this->memberModel->where(array('uid'=>$uid))->find();
        if($cuser['refer_uid']!=$this->memberinfo['uid']) {
            return_json(1,'该用户不是您的下级');
        }
        if($grade_id>$this->memberinfo['grade_id']) {
            return_json(1,'无法调整');
        }
        if($grade_id>4) {
            return_json(1,'最高只能调整为合伙人');
        }
        $save = array(
            'grade_id' => $grade_id
        );
        $this->memberModel->where(array('uid'=>$uid))->save($save);
        return_json(0,'修改成功');
    }
    
    public function getuserinfo () {
        $mobile = get('uid');
        $user = $this->memberModel->where(array('mobile'=>$mobile))->field('uid,realname,nickname,grade_id,mobile,refer_uid')->find();
        if(!$user) {
            return_json(1,'报单用户不存在');
        }
        return_json(0,'ok',$user);
    }
    
     
}